package cn.edu.sdjzu.cs.dingcan.servlet;

import cn.edu.sdjzu.cs.dingcan.service.CustomerService;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "CustomerLoginServlet", urlPatterns = {"/customer-login", "/customer-login-process", "/customer-logout"})
public class CustomerLoginServlet extends HttpServlet {

    /**
     * 登入处理
     * @param request
     * @param response
     * @throws IOException
     */
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if(request.getRequestURI().endsWith("customer-login-process")) {   // 如果以POST方式请求login
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String goTo = request.getContextPath();
            HttpSession session = request.getSession();
            session.removeAttribute("loginError");
            if(StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
                session.setAttribute("loginError", "请输入用户名和密码");
                goTo = goTo + "/customer-login";
            } else {
                CustomerService customerService = new CustomerService();
                try {
                    if(customerService.login(username, password, request.getSession())) {
                        goTo = StringUtils.defaultIfBlank(request.getParameter("referer"), request.getContextPath());
                    } else {
                    	session.setAttribute("loginError", "用户名或密码错误");
                    	goTo = goTo + "/customer-login";
                    }
                } catch (SQLException throwables) {
                    throw new RuntimeException("执行数据库操作时遇到异常", throwables);
                }
            }
            response.sendRedirect(goTo);
        } else {
            response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
    }

    /**
     * 登出（注销）处理
     * @param request
     * @param response
     * @throws IOException
     */
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        if(request.getRequestURI().endsWith("customer-logout")) {   // 注销
            request.getSession().invalidate();
            response.sendRedirect(request.getContextPath());
        } else if(request.getRequestURI().endsWith("customer-login")) { // 显示独立的登录页
            request.getRequestDispatcher("/app/detail/customer-login.jsp").forward(request, response);
        } else {
                response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
    }
}
